package com.jinjie.config.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;

@Slf4j
public class IllegalRequestFilter implements Filter {

    // 定义非法字符的正则表达式
    private static final Pattern ILLEGAL_PATTERN = Pattern.compile("[<>'\"%;&()/\\\\]");
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String contextPath = httpRequest.getContextPath();
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String requestURI = httpRequest.getRequestURI();
        log.info("requestURI is {}",requestURI);
        if (!requestURI.startsWith(contextPath)) {
            // 对于不在 context-path 内的请求，返回 404 错误

            httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
            httpResponse.getWriter().write("The requested page was not found.");
            return ;
        }
        chain.doFilter(request, response);
    }
    private boolean isIllegalRequest(String requestURI) {
        return ILLEGAL_PATTERN.matcher(requestURI).find();
    }
}
